<template>
  <div class="order-create-container container">
    <div class="page-header">
      <el-page-header @back="goBack" content="创建订单"></el-page-header>
    </div>
    
    <div class="order-create card" v-loading="loading">
      <!-- 车辆信息 -->
      <div class="vehicle-info">
        <h3 class="section-title">车辆信息</h3>
        <div class="vehicle-card">
          <div class="vehicle-image">
            <img :src="vehicle.imageUrl" :alt="vehicle.name">
          </div>
          <div class="vehicle-detail">
            <h4 class="vehicle-name">{{ vehicle.name }}</h4>
            <div class="vehicle-meta">
              <span><i class="el-icon-odometer"></i> {{ vehicle.type }}</span>
              <span><i class="el-icon-user"></i> {{ vehicle.seats }}座</span>
              <span><i class="el-icon-set-up"></i> {{ vehicle.transmission }}</span>
            </div>
            <div class="vehicle-price">
              <span class="price">¥{{ vehicle.dailyPrice }}</span>
              <span class="unit">/天</span>
            </div>
          </div>
        </div>
      </div>
      
      <el-divider></el-divider>
      
      <!-- 租车信息 -->
      <div class="rental-info">
        <h3 class="section-title">租车信息</h3>
        <el-form :model="rentalForm" :rules="rentalRules" ref="rentalForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12">
              <el-form-item label="取车日期" prop="startDate">
                <el-date-picker
                  v-model="rentalForm.startDate"
                  type="date"
                  placeholder="选择取车日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                  :picker-options="startDateOptions"
                  @change="calculateDays"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="还车日期" prop="endDate">
                <el-date-picker
                  v-model="rentalForm.endDate"
                  type="date"
                  placeholder="选择还车日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                  :picker-options="endDateOptions"
                  @change="calculateDays"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="租期">
            <span class="rental-days">{{ rentalDays }}天</span>
          </el-form-item>
          
          <el-form-item label="取车门店" prop="pickupStore">
            <el-select v-model="rentalForm.pickupStore" placeholder="请选择取车门店" style="width: 100%">
              <el-option
                v-for="item in stores"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="还车门店" prop="returnStore">
            <el-select v-model="rentalForm.returnStore" placeholder="请选择还车门店" style="width: 100%">
              <el-option
                v-for="item in stores"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      
      <el-divider></el-divider>
      
      <!-- 费用明细 -->
      <div class="payment-details">
        <h3 class="section-title">费用明细</h3>
        <div class="price-item">
          <span class="label">车辆租金：</span>
          <span class="value">¥{{ rentalAmount }}</span>
        </div>
        <div class="price-item">
          <span class="label">服务费：</span>
          <span class="value">¥{{ serviceFee }}</span>
        </div>
        <div class="price-item">
          <span class="label">押金：</span>
          <span class="value">¥{{ vehicle.deposit || 2000 }}</span>
        </div>
        <div class="price-item total">
          <span class="label">合计：</span>
          <span class="value">¥{{ totalAmount }}</span>
        </div>
        <div class="price-note">
          <p>* 押金将在还车时退还</p>
        </div>
      </div>
      
      <!-- 提交订单 -->
      <div class="submit-order">
        <el-button type="primary" size="large" @click="handleSubmit" :loading="submitting">提交订单</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getVehicleDetail } from '@/api/vehicle'
import { createOrder, calculatePrice } from '@/api/order'
import { getStoreList } from '@/api/store'

export default {
  name: 'OrderCreate',
  data() {
    return {
      loading: false,
      submitting: false,
      vehicle: {
        id: 0,
        name: '',
        type: '',
        seats: 0,
        transmission: '',
        dailyPrice: 0,
        deposit: 0,
        imageUrl: ''
      },
      rentalForm: {
        startDate: '',
        endDate: '',
        pickupStore: '',
        returnStore: ''
      },
      rentalRules: {
        startDate: [
          { required: true, message: '请选择取车日期', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '请选择还车日期', trigger: 'change' }
        ],
        pickupStore: [
          { required: true, message: '请选择取车门店', trigger: 'change' }
        ],
        returnStore: [
          { required: true, message: '请选择还车门店', trigger: 'change' }
        ]
      },
      stores: [
        { id: 1, name: '北京朝阳门店' },
        { id: 2, name: '北京海淀门店' },
        { id: 3, name: '北京西城门店' },
        { id: 4, name: '北京东城门店' }
      ],
      serviceFee: 50
    }
  },
  computed: {
    startDateOptions() {
      return {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7 // 不能选择今天之前的日期
        }
      }
    },
    endDateOptions() {
      return {
        disabledDate: (time) => {
          if (!this.rentalForm.startDate) {
            return time.getTime() < Date.now() - 8.64e7
          }
          const startDate = new Date(this.rentalForm.startDate)
          return time.getTime() < startDate.getTime()
        }
      }
    },
    rentalDays() {
      if (!this.rentalForm.startDate || !this.rentalForm.endDate) {
        return 0
      }
      
      const startDate = new Date(this.rentalForm.startDate)
      const endDate = new Date(this.rentalForm.endDate)
      const timeDiff = endDate.getTime() - startDate.getTime()
      return Math.ceil(timeDiff / (1000 * 3600 * 24))
    },
    rentalAmount() {
      return this.vehicle.dailyPrice * this.rentalDays
    },
    totalAmount() {
      return this.rentalAmount + this.serviceFee
    }
  },
  created() {
    this.initFromQuery()
    this.fetchVehicleDetail()
    this.fetchStores()
  },
  methods: {
    initFromQuery() {
      const { query } = this.$route
      
      if (query.startDate) {
        this.rentalForm.startDate = query.startDate
      }
      
      if (query.endDate) {
        this.rentalForm.endDate = query.endDate
      }
    },
    fetchVehicleDetail() {
      this.loading = true
      const vehicleId = this.$route.query.vehicleId
      
      if (!vehicleId) {
        this.$message.error('未指定车辆')
        this.$router.push('/vehicle/list')
        return
      }
      
      getVehicleDetail(vehicleId)
        .then(response => {
          if (response.code === 200 && response.data) {
            this.vehicle = {
              id: response.data.id,
              name: response.data.name,
              type: response.data.typeName || response.data.type,
              seats: response.data.seats,
              transmission: response.data.transmissionName || response.data.transmission,
              dailyPrice: response.data.dailyPrice,
              deposit: response.data.deposit || 2000,
              imageUrl: response.data.imageUrl || 'https://img2.baidu.com/it/u=306367250,2071323421&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=500'
            }
          } else {
            this.$message.error('获取车辆信息失败')
            this.$router.push('/vehicle/list')
          }
        })
        .catch(error => {
          console.error('获取车辆详情失败', error)
          this.$message.error('获取车辆信息失败，请稍后重试')
          this.$router.push('/vehicle/list')
        })
        .finally(() => {
          this.loading = false
        })
    },
    calculateDays() {
      if (!this.rentalForm.startDate || !this.rentalForm.endDate) {
        return
      }
      
      const startDate = new Date(this.rentalForm.startDate)
      const endDate = new Date(this.rentalForm.endDate)
      const timeDiff = endDate.getTime() - startDate.getTime()
      const days = Math.ceil(timeDiff / (1000 * 3600 * 24))
      
      if (days > 0) {
        // 调用后端API计算价格
        this.calculateRentalPrice()
      }
    },
    goBack() {
      this.$router.go(-1)
    },
    handleSubmit() {
      this.$refs.rentalForm.validate(valid => {
        if (valid) {
          this.submitting = true
          
          // 构建订单数据
          const orderData = {
            vehicleId: this.vehicle.id,
            startDate: this.rentalForm.startDate,
            endDate: this.rentalForm.endDate,
            pickupStoreId: this.rentalForm.pickupStore,
            returnStoreId: this.rentalForm.returnStore,
            duration: this.rentalDays,
            amount: this.totalAmount,
            deposit: this.vehicle.deposit
          }
          
          // 调用创建订单API
          createOrder(orderData).then(response => {
            this.submitting = false
            if (response.code === 200) {
              this.$message({
                message: '订单创建成功',
                type: 'success'
              })
              // 跳转到我的订单页面
              this.$router.push('/order/list')
            } else {
              this.$message.error(response.message || '订单创建失败')
            }
          }).catch(error => {
            this.submitting = false
            this.$message.error('订单创建失败：' + error.message)
          })
        } else {
          return false
        }
      })
    },
    fetchStores() {
      this.loading = true
      // 调用门店列表API
      getStoreList()
        .then(response => {
          if (response.code === 200 && response.data) {
            this.stores = response.data || [];
            if (this.stores.length > 0) {
              // 默认选中第一个门店
              this.rentalForm.pickupStore = this.stores[0].id;
              this.rentalForm.returnStore = this.stores[0].id;
            }
          } else {
            // 如果API调用失败，使用默认数据
            this.$message.warning('获取门店列表失败，使用默认数据');
            this.stores = [
              { id: 1, name: '北京朝阳门店' },
              { id: 2, name: '北京海淀门店' },
              { id: 3, name: '北京西城门店' },
              { id: 4, name: '北京东城门店' }
            ];
            this.rentalForm.pickupStore = this.stores[0].id;
            this.rentalForm.returnStore = this.stores[0].id;
          }
        })
        .catch(error => {
          console.error('获取门店列表失败', error);
          this.$message.error('获取门店列表失败，请稍后重试');
          // 出错时使用默认数据
          this.stores = [
            { id: 1, name: '北京朝阳门店' },
            { id: 2, name: '北京海淀门店' },
            { id: 3, name: '北京西城门店' },
            { id: 4, name: '北京东城门店' }
          ];
          this.rentalForm.pickupStore = this.stores[0].id;
          this.rentalForm.returnStore = this.stores[0].id;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    calculateRentalPrice() {
      if (!this.rentalForm.startDate || !this.rentalForm.endDate || !this.vehicle.id) {
        return
      }
      
      const params = {
        vehicleId: this.vehicle.id,
        startDate: this.rentalForm.startDate,
        endDate: this.rentalForm.endDate
      }
      
      calculatePrice(params)
        .then(response => {
          if (response.code === 200 && response.data) {
            this.serviceFee = response.data.serviceFee || 50
            // 如果后端返回了总租金，使用后端计算的值
            if (response.data.rentalAmount) {
              this.vehicle.dailyPrice = response.data.rentalAmount / this.rentalDays
            }
          }
        })
        .catch(error => {
          console.error('计算价格失败', error)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.order-create-container {
  padding: 20px 0;
  
  .page-header {
    margin-bottom: 20px;
  }
  
  .card {
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
    margin-bottom: 20px;
  }
  
  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin-top: 0;
    margin-bottom: 20px;
    color: #303133;
  }
  
  .vehicle-card {
    display: flex;
    
    .vehicle-image {
      width: 160px;
      height: 100px;
      overflow: hidden;
      margin-right: 20px;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    
    .vehicle-detail {
      .vehicle-name {
        font-size: 16px;
        margin-top: 0;
        margin-bottom: 10px;
      }
      
      .vehicle-meta {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 10px;
        
        span {
          margin-right: 15px;
          margin-bottom: 5px;
          color: #606266;
          
          i {
            margin-right: 5px;
          }
        }
      }
      
      .vehicle-price {
        .price {
          font-size: 18px;
          font-weight: bold;
          color: #f56c6c;
        }
        
        .unit {
          font-size: 12px;
          color: #999;
        }
      }
    }
  }
  
  .rental-days {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }
  
  .payment-details {
    .price-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      
      &.total {
        margin-top: 15px;
        padding-top: 15px;
        border-top: 1px solid #ebeef5;
        
        .label, .value {
          font-size: 16px;
          font-weight: bold;
        }
        
        .value {
          color: #f56c6c;
        }
      }
      
      .label {
        color: #606266;
      }
      
      .value {
        color: #303133;
      }
    }
    
    .price-note {
      margin-top: 10px;
      color: #909399;
      font-size: 12px;
    }
  }
  
  .submit-order {
    margin-top: 30px;
    text-align: center;
  }
}

@media (max-width: 768px) {
  .order-create-container {
    .vehicle-card {
      flex-direction: column;
      
      .vehicle-image {
        width: 100%;
        margin-right: 0;
        margin-bottom: 15px;
      }
    }
  }
}
</style> 